<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px">
      <el-form-item label="小区" prop="areaName">
        <el-select v-model="queryParams.areaName" :filter-method="filterMethod" allow-create clearable
                   default-first-option filterable
                   placeholder="请输入小区" size="small" @change="getGroup(queryParams.areaName)">
          <el-option v-for="(item, index) in areaIdOptions" :key="index" :disabled="item.disabled"
                     :label="item.areaName" :value="item.areaName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="楼宇" prop="groupName">
        <el-select v-model="queryParams.groupName" clearable placeholder="请输入楼宇" size="small"
                   @change="getUnit(queryParams.areaName,queryParams.groupName)">
          <el-option v-for="(item, index) in groupIdOptions" :key="index" :disabled="item.disabled"
                     :label="item.groupName" :value="item.groupName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="单元" prop="unitName">
        <el-select v-model="queryParams.unitName" clearable placeholder="请输入单元" size="small">
          <el-option v-for="(item, index) in unitNameOptions" :key="index" :disabled="item.disabled"
                     :label="item.unitName" :value="item.unitName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="户" prop="doorName">
        <el-input
          v-model="queryParams.doorName" clearable
          placeholder="请输入户名称"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="userName">
        <el-input
          v-model="queryParams.userName" clearable
          placeholder="请输入姓名"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房屋编号" prop="houseId">
        <el-input
          v-model="queryParams.houseId" clearable
          placeholder="请输入房屋编号"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="缴费状态" prop="costSts">
        <el-select v-model="queryParams.costSts" clearable placeholder="请选择缴费状态" size="small">
          <el-option
            v-for="dict in dict.type.COST001"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="缴费渠道" prop="costWay">
        <el-select v-model="queryParams.costWay" clearable placeholder="请选择缴费渠道" size="small">
          <el-option
            v-for="dict in dict.type.COST002"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="对账状态" prop="checkSts">
              <el-select v-model="queryParams.checkSts" placeholder="请选择对账状态" clearable>
                <el-option
                  v-for="dict in dict.type.COST003"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>-->
      <el-form-item label="发票号码" prop="billNo">
        <el-input
          v-model="queryParams.billNo"
          clearable
          placeholder="请输入发票号码"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="面积" prop="space">
        <el-input
          v-model="queryParams.space"
          clearable
          placeholder="请输入面积"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="缴费日期">
        <el-date-picker
          v-model="dateRange"
          end-placeholder="结束日期"
          range-separator="-"
          size="small"
          start-placeholder="开始日期"
          style="width: 240px"
          type="daterange"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" type="primary" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh"  size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          icon="el-icon-download"
          plain
          size="mini"
          type="warning"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-download"
          plain
          size="mini"
          type="warning"
          @click="handleApply"
        >申请发票
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-download"
          plain
          size="mini"
          type="warning"
          @click="downloadProof"
        >下载证明
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div ref="print" class="print-wrap" hidden>
      <div :style="{ width: '320px' }" class="print-preview">
        <div class="title">打印票据</div>
        <div class="divide_line"></div>
        <!-- ...小票内容html -->
        <div class="tip">请保存好小票，不要丢弃！</div>
        <!-- 底下logo二进制文件流，一定要用二进制文件流，保证浏览器打印能够拿到log -->
        <!-- <img class="image-wrap" src="data:image/png;base64,二进制文件流">-->
        <div id="year" class="div1">ddd</div>
        <div id="month" class="div2"></div>
        <div id="date" class="div3"></div>
        <div id="userName" class="div5"></div>
        <div id="space" class="div6"></div>
        <div id="addr" class="div7"></div>
        <div id="tel" class="div8"></div>
        <div id="formula" class="div10"></div>
        <div id="moneyTemp" class="div11"></div>
        <div id="money" class="div12"></div>
        <div id="unit" class="div13"></div>
      </div>
    </div>

    <el-table v-loading="loading" :cell-style="tableRowClassName" :data="costQueryList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column align="center" label="地址" prop="addr" width="200"/>
      <el-table-column :formatter="numberFormat" align="center" label="面积" prop="space"/>
      <el-table-column align="center" label="姓名" prop="userName" width="120"/>
      <el-table-column align="center" label="房屋编号" prop="houseId"/>
      <el-table-column align="center" label="流水号" prop="serial"width="200"/>
      <el-table-column :show-overflow-tooltip="true" align="center" label="电子票">
        <template slot-scope="scope">
          <span style="color:#007aff" @click="openCard(scope.row.billHttp)">{{ scope.row.billName }}</span>
        </template>
      </el-table-column>
      <el-table-column :formatter="numberFormat" align="center" label="缴费金额" prop="costMoney" width="100"/>
      <el-table-column align="center" label="缴费时间" prop="costDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.costDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="缴费状态" prop="costSts">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.COST001" :value="scope.row.costSts"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="缴费渠道" prop="costWay">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.COST002" :value="scope.row.costWay"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="对账状态" prop="checkSts">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.COST003" :value="scope.row.checkSts"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="发票号码" prop="billNo"width="200"/>
      <el-table-column align="center" label="收费员" prop="creater"/>
      <el-table-column align="center" label="备注" prop="remark"/>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />
    <el-dialog :title="titleCard" :visible.sync="showCard" append-to-body width="700px">
      <div style="text-align:center">
        <img :src="cardUrl" style="width:600px"/>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="showCard=false">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {listCostQuery, listCostQuery1, getPrint, applyCostQuery, downloadProof} from "@/api/fund/costQuery";
import {getAreaInfo, getAreaInfo1} from "@/api/house/area";
import {getGroupInfo} from "@/api/house/group";
import {getUnitInfo} from "@/api/house/unit";

export default {
  name: "CostQuery",
  dicts: ['COST003', 'COST002', 'COST001'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 缴费信息表格数据
      costQueryList: [],
      // 日期范围
      dateRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        houseId: null,
        areaName: null,
        startDate: null,
        space: null,
        endDate: null,
        costSts: null,
        costWay: null,
        checkSts: null,
        userName: null,
        billNo: null,
      },
      areaIdOptions: [{}],
      groupIdOptions: [{}],
      unitNameOptions: [{}],
      cardUrl: '',
      titleCard: '',
      showCard: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList1();
    this.areaSelect();
    this.filterMethod();
  },
  methods: {
    numberFormat(row, column, cellValue) {
      cellValue += ''
      if (!cellValue.includes('.')) cellValue += '.'
      return cellValue.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
        return $1 + ','
      }).replace(/\.$/, '')
    },
    filterMethod(val) {
      this.value = val
      getAreaInfo1(this.value).then(response => {
        this.areaIdOptions = response.rows;
      });
    },
    areaSelect() {
      getAreaInfo().then(response => {
        this.areaIdOptions = response.rows;
      });
    },
    getGroup(areaName) {
      if (areaName != "") {
        getGroupInfo(areaName).then(response => {
          this.groupIdOptions = response.rows;
        });
      }
    },
    getUnit(areaName, groupName) {
      getUnitInfo(areaName, groupName).then(response => {
        this.unitNameOptions = response.rows;
      });
    },
    openCard(id, name) {
      window.open(id, '_blank')
    },
    tableRowClassName({row}) {
      return row.costSts == '1' ? 'color: black;' : (row.costSts == '2' ? 'color: red;' : "")
    },
    /** 查询缴费信息列表 */
    getList() {
      debugger
      this.loading = true;
      listCostQuery(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.costQueryList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.areaSelect();
      });
    },
    /** 查询缴费信息列表 */
    getList1() {
      this.loading = true;
      listCostQuery1(this.queryParams).then(response => {
        this.costQueryList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.areaSelect();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        costId: null,
        houseId: null,
        serial: null,
        costMoney: null,
        costDate: null,
        costSts: null,
        costWay: null,
        checkSts: null,
        space: null,
        billNo: null,
        userName: null,
        creater: null,
        createDate: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery1() {
      this.queryParams.pageNum = 1;
      this.getList1();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.areaSelect();
      this.resetForm("queryForm");
      this.dateRange = [];
      this.handleQuery1();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.costId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    handleApply(row) {
      const costId = row.costId || this.ids
      this.$modal.confirm('是否确认申请缴费信息编号为"' + costId + '"的电子票？').then(function () {
        return applyCostQuery(costId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("申请成功");
        window.open("ooo://", '_blank')
      }).catch(() => {
      });
    },

    downloadProof(row) {
      const costId = row.costId || this.ids
      return downloadProof(costId).then(response => {
        let baseUrl = "http://" + response.data.addr;
        window.open(baseUrl);
      });
    },

    onPrint(row) {
      this.reset();
      const costId = row.costId || this.ids
      getPrint(costId).then(response => {
        const printNode = this.$refs.print
        if (!printNode) return
        const newIframe = document.createElement('iframe');
        newIframe.setAttribute('style', 'width:0px;height:0px;position:absolute;left:-9999px;top:-9999px;');
        newIframe.setAttribute('align', 'center');
        document.body.appendChild(newIframe);
        document.getElementById("year").innerHTML = response.data.year;
        document.getElementById("money").innerHTML = response.data.costMoney;
        document.getElementById("date").innerHTML = response.data.costDate;
        document.getElementById("userName").innerHTML = response.data.userName;
        document.getElementById("space").innerHTML = response.data.space;
        document.getElementById("addr").innerHTML = response.data.addr;
        document.getElementById("tel").innerHTML = response.data.tel;
        document.getElementById("formula").innerHTML = response.data.formula;
        document.getElementById("moneyTemp").innerHTML = response.data.moneyTemp;
        document.getElementById("month").innerHTML = response.data.month;
        document.getElementById("unit").innerHTML = "房产管理局物业管理办公室";
        let doc = null;
        doc = newIframe.contentWindow.document;
        doc.write(`
            <style type="text/css">
              @media print {
                @page {
                  size: auto;
                  margin: 1mm;
                  table { page-break-after: auto; }
                  tr    { page-break-inside: avoid; page-break-after: auto; }
                  td    { page-break-inside: avoid; page-break-after: auto; }
                  thead { display: table-header-group; }
                  tfoot { display: table-footer-group; }
                }
              }
              .print-preview { display: flex; flex-direction: column; color: rgba(51, 51, 51, 1); font-family: Microsoft YaHei, '黑体', STSong, '宋体',Consolas, Monaco, Droid, Sans, Mono, Source, Code, Pro, Menlo, Lucida, Sans, Type, Writer, Ubuntu, Mono; }
              .title { display: flex; justify-content: center; font-size: 21px; height: 50px; line-height: 50px; font-weight: bold; }
              .divide_line { justify-content: center; border-bottom: 1px dashed rgba(51, 51, 51, 1); }
              body{
                          margin:0;
                      }
                      .main {
                          width: 1470px;
              		    height: 622px;
              		    border: 0px #000 solid;
                          color: #000;
                          font-weight:bold;
                          line-height: 13px;
                          font-size: 28px;
                          position: relative;
                      }
                      .main div{
                          z-index: 11;
                          position: absolute;
                          /*background:#0f0;*/
                          height: 13px;
                      }
                      .img1{
                          width: 100%;
                          position: absolute;
                          top:0;
                          z-index: 1;
                          display: none;
                      }
                      .div1{
                          top: 200px;
                          left: 300px;
                          width: 100px;
                      }
                      .div2{
                          top: 83px;
                          left: 300px;
                          width: 100px;
                      }
                      .div3{
                          top: 83px;
                          left: 390px;
                          width: 100px;
                      }

                      .div5{
                          top: 140px;
                          left: 300px;
                          width: 300px;
                      }
                      .div6{
                          top: 140px;
                          left: 855px;
                          width: 400px;
                      }
                      .div7{
                          top: 224px;
                          left: 300px;
                          width: 500px;
                      }
                      .div8{
                          top: 224px;
                          left: 885px;
                          width: 300px;
                      }

                      .div10{
                          top: 300px;
                          left: 300px;
                          width: 600px;
                      }
              		.div11{
                          top: 440px;
                          left: 300px;
                          width: 330px;
                      }
              		.div12{
              			top: 447px;
              			left: 920px;
              			width: 300px;
              		}
              		.div13{
              			top: 500px;
              			left: 300px;
              			width: 300px;
              		}

              		.div14{
              			top: 500px;
              			left: 643px;
              			width: 300px;
              		}
            </style>
            <div style="width:100%;height:auto;width:320px;margin:0px auto;"align="center">
              ${printNode.innerHTML}
            </div>`)
        doc.close();
        setTimeout(() => {
          newIframe.contentWindow.focus();
          newIframe.contentWindow.print();
          document.body.removeChild(newIframe);
        }, 10);
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('/fund/costQuery/export', {
        ...this.queryParams
      }, `缴费查询_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style>

</style>

